// 动态路由生成工具
import { defineAsyncComponent } from 'vue'

// 组件映射表 - 根据菜单路径映射到对应的组件
const componentMap = {
  '/dashboard': () => import('@/views/admin/Dashboard.vue'),
  '/system/user': () => import('@/views/admin/system/UserManagement.vue'),
  '/system/role': () => import('@/views/admin/system/RoleManagement.vue'),
  '/system/permission': () => import('@/views/admin/system/PermissionManagement.vue'),
  '/system/group': () => import('@/views/admin/system/GroupManagement.vue'),
  '/profile': () => import('@/views/admin/Profile.vue')
}

// 默认组件 - 当找不到对应组件时使用
const DefaultComponent = defineAsyncComponent(() => import('@/components/DefaultPage.vue'))

/**
 * 根据菜单数据生成路由配置
 * @param {Array} menuTree - 菜单树数据
 * @returns {Array} 路由配置数组
 */
export function generateRoutes(menuTree) {
  const routes = []
  
  const processMenu = (menu) => {
    // 只处理菜单类型的项目
    if (menu.type === 1 && menu.isLeaf) {
      const routePath = menu.path.startsWith('/') ? menu.path.substring(1) : menu.path
      
      const route = {
        path: routePath,
        name: menu.code.replace(/[:\-]/g, '_'), // 将特殊字符替换为下划线
        component: componentMap[menu.path] || (() => DefaultComponent),
        meta: {
          title: menu.name,
          icon: menu.icon,
          code: menu.code,
          id: menu.id,
          requiresAuth: true,
          keepAlive: true
        }
      }
      
      routes.push(route)
    }
    
    // 递归处理子菜单
    if (menu.children && menu.children.length > 0) {
      menu.children.forEach(child => processMenu(child))
    }
  }
  
  menuTree.forEach(menu => processMenu(menu))
  
  return routes
}

/**
 * 动态添加路由到路由器
 * @param {Object} router - Vue Router实例
 * @param {Array} menuTree - 菜单树数据
 */
export function addDynamicRoutes(router, menuTree) {
  const dynamicRoutes = generateRoutes(menuTree)
  
  // 获取admin路由
  const adminRoute = router.getRoutes().find(route => route.name === 'Admin')
  
  if (adminRoute) {
    // 添加动态路由到admin路由的children中
    dynamicRoutes.forEach(route => {
      router.addRoute('Admin', route)
    })
    
    console.log('✅ 动态路由添加成功:', dynamicRoutes.length, '个路由')
    console.log('📋 路由列表:', dynamicRoutes.map(r => ({ path: r.path, name: r.name, title: r.meta.title })))
  } else {
    console.error('❌ 未找到Admin父路由')
  }
}

/**
 * 清除动态路由
 * @param {Object} router - Vue Router实例
 * @param {Array} menuTree - 菜单树数据
 */
export function removeDynamicRoutes(router, menuTree) {
  const dynamicRoutes = generateRoutes(menuTree)
  
  dynamicRoutes.forEach(route => {
    if (router.hasRoute(route.name)) {
      router.removeRoute(route.name)
    }
  })
  
  console.log('🗑️ 动态路由清除完成')
}

/**
 * 检查组件是否存在
 * @param {String} path - 菜单路径
 * @returns {Boolean} 组件是否存在
 */
export function hasComponent(path) {
  return path in componentMap
}

/**
 * 获取缺失的组件列表
 * @param {Array} menuTree - 菜单树数据
 * @returns {Array} 缺失组件的菜单项
 */
export function getMissingComponents(menuTree) {
  const missing = []
  
  const processMenu = (menu) => {
    if (menu.type === 1 && menu.isLeaf && !hasComponent(menu.path)) {
      missing.push({
        name: menu.name,
        path: menu.path,
        code: menu.code
      })
    }
    
    if (menu.children && menu.children.length > 0) {
      menu.children.forEach(child => processMenu(child))
    }
  }
  
  menuTree.forEach(menu => processMenu(menu))
  
  return missing
}

/**
 * 根据菜单路径获取路由名称
 * @param {String} path - 菜单路径
 * @param {String} code - 菜单代码
 * @returns {String} 路由名称
 */
export function getRouteName(path, code) {
  return code.replace(/[:\-]/g, '_')
}

/**
 * 根据菜单数据生成面包屑
 * @param {Array} menuTree - 菜单树数据
 * @param {String} currentPath - 当前路径
 * @returns {Array} 面包屑数组
 */
export function generateBreadcrumb(menuTree, currentPath) {
  const breadcrumb = []
  
  const findPath = (menus, targetPath, path = []) => {
    for (const menu of menus) {
      const currentBreadcrumb = [...path, { name: menu.name, path: menu.path, code: menu.code }]
      
      if (menu.path === targetPath) {
        breadcrumb.push(...currentBreadcrumb)
        return true
      }
      
      if (menu.children && menu.children.length > 0) {
        if (findPath(menu.children, targetPath, currentBreadcrumb)) {
          return true
        }
      }
    }
    return false
  }
  
  findPath(menuTree, currentPath)
  return breadcrumb
}

export default {
  generateRoutes,
  addDynamicRoutes,
  removeDynamicRoutes,
  hasComponent,
  getMissingComponents,
  getRouteName,
  generateBreadcrumb
}